﻿using Batman.SQLScripts;
using Microsoft.AspNetCore.Hosting;
using System;
using System.IO;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class SQLScriptExtension
    {
        public static void AddBatmanSQLScripts(this IServiceCollection services, Action<ScriptOptions> optionsAction)
        {
            var options = new ScriptOptions();

            optionsAction(options); // 设置路径

            if (string.IsNullOrEmpty(options.DirectoryFullPath))
            {
                var env = services.BuildServiceProvider().GetService<IHostingEnvironment>();

                // 默认在根目录下，因为在APP_DATA下可能有读权限问题
                SQLScript.ScriptPath = Path.Combine(env.ContentRootPath, "Maps");
            }
            else
            {
                SQLScript.ScriptPath = Path.Combine(options.DirectoryFullPath);
            }
            if (!Directory.Exists(SQLScript.ScriptPath)) Directory.CreateDirectory(SQLScript.ScriptPath);

            SQLScript.LoadScripts();
        }

        public static void AddBatmanSQLScripts(this IServiceCollection services)
        {
            services.AddBatmanSQLScripts(options => { });
        }
    }
}
